var express = require('express')
    , stock = require('tushare').stock
    , route = express.Router()
    , logger = require('log4js').getLogger('user.index.js');

var util = require('../../util');

route.use((req, res, next) => {
    logger.info(req.originalUrl);
    next();
});

route.get('/', (req, res) => {
    res.send('welcome stock index');
});

// 获取历史信息
route.get('/getHistory', (req, res) => {
    const code = req.query.code || '600848',  // 默认大盘指数
        ktype = req.query.type || 'week',
        // 默认一个月前的今天为开始
        start = req.query.start || util.date.getDateStr(new Date() - 1000 * 60 * 60 * 24 * 30),
        // 默认今天结束
        end = req.query.end || util.date.getDateStr();

    const options = { code, ktype };

    stock.getHistory(options).then(({ data }) => {

        // console.log(data.record.length);

        if (data && data.record && data.record.length > 0) {
            var record = [];
            for (let k in data.record) {
                let date = data.record[k][0];
                if (date >= start && date <= end) {
                    record.push(data.record[k]);
                }
            }
            res.send({ code, ktype, start, end, record });
        }
        else {
            res.send({ msg: 'no result!', data: data });
        }
        
    });
});

// 获取历史分笔数据
route.get('/getTick', (req, res) => {
    const options = {
        code: '600848',
        date: '2015-12-31'
    };
    stock.getTick(options).then(({ data }) => {
        console.log(data);
        // [["15:00:00", "22.97", "-0.01", "0", "0", "卖盘"], ..., ["09:25:02", "21.9", "21.9", "77", "168630", "买盘"]]
        // 返回格式：成交时间 成交价  涨跌幅  价格变动  成交量(手)  成交额(元)  性质
        res.send(data);
    });
});

// 一次性获取最近一个日交易日所有股票的交易数据
// `options(可选)` 参数说明：
// {
//   pageSize: 设置单次返回股票的数量，默认10000，即全部股票
//   pageNo: 页码，都懂得
// }
//  * 返回数据格式：代码，名称，涨跌幅，现价，开盘价，最高价，最低价，最日收盘价，成交量，换手率
route.get('/getTodayAll', (req, res) => {
    const options = {
        pageSize: req.query.record || 10000,
        pageNo: req.query.page || 1
    };
    stock.getTodayAll(options).then(({ data }) => {
        console.log(data);
        // [{ "symbol": "sz300675", "code": "300675", "name": "N建科院", "trade": "5.270", "pricechange": "1.610", "changepercent": "43.989", "buy": "5.270", "sell": "0.000", "settlement": "3.660", "open": "4.390", "high": "5.270", "low": "4.390", "volume": 14900, "amount": 78391, "ticktime": "13:57:39", "per": 18.382, "pb": 2.011, "mktcap": 77293.3509, "nmc": 19323.3509, "turnoverratio": 0.04064 }, ..., {}]
        res.send(data);
    });
});

// getLiveData - 获取实时交易数据
route.get('/getLiveData', (req, res) => {
    let codes;
    if (typeof req.query.codes === 'string') {
        codes = [req.query.codes];
    } 
    else {
        codes = req.query.codes;
    }
    const options = {codes};
    stock.getLiveData(options).then(({ data }) => {
        console.log(data);
        res.send(data);
    });
});


route.get('/about', (req, res) => {
    res.send('about stock');
});

module.exports = route;